<template>
  <el-popover
    placement="bottom"
    width="300"
    v-model="popoverVisible"
    trigger="click"
    popper-class="tag-selector"
    @show="openPanel"
  >
    <div class="search-box">
      <el-input v-model="keyword" placeholder="搜索关键字" prefix-icon="el-icon-search" @keyup.native.enter="search">
        <i class="el-icon-close" slot="suffix" @click="clearSearch" v-if="keyword.length"></i>
      </el-input>
    </div>
    <div v-if="selected.length && selected[selected.length - 1].catalogId" class="tab-title">
      <icon-svg name="iconReturn" @click.native="prev"></icon-svg>
      <el-breadcrumb separator="/" ref="factoryBread">
        <div class="elli" v-if="breadLeft < 0">...</div>
        <el-breadcrumb-item
          v-for="(item, index) in selected"
          :key="index"
          :class="{ normal: index === selected.length - 1 }"
          :style="index === 0 ? { marginLeft: breadLeft + 'px' } : null"
          @click.native="changeTab(index)"
          >{{ item.catalogNm }}</el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <template v-if="showList.length && showList[0].assetId">
      <ul>
        <li v-for="item in showList" :key="item.assetId" class="tag-item" @click="handleClick(item)">
          <div class="asset-name">{{ item.assetNm }}</div>
          <div class="list-handler">
            <el-tooltip effect="dark" placement="top" :enterable="false">
              <span slot="content">
                口径：{{ item.bizStmt }}
                <template v-if="item.plfmDataDate">
                  <br />
                  <br />
                  数据日期: {{ item.plfmDataDate }}
                </template>
              </span>
              <icon-svg name="iconPreview"></icon-svg>
            </el-tooltip>
          </div>
        </li>
      </ul>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="params.currentPageNum"
        :page-size="params.pageSize"
        :pager-count="5"
        background
        layout="total, prev, pager, next"
        small
        :total="totalSize"
      >
      </el-pagination>
    </template>
    <ul v-else-if="showList.length && showList[0].catalogId" class="catalog-list tag-scrollbar">
      <li v-for="item in showList" :key="item.catalogId" @click="handleClickCatalog(item)">
        {{ item.catalogNm }} （{{ item.dataAssetCount }}）
        <i class="el-icon-arrow-right"></i>
      </li>
    </ul>
    <p v-else>暂无内容</p>
    <span slot="reference" class="selector-tag">{{ tagInfo.tagId ? tagInfo.tagNm : '请选择' }}</span>
  </el-popover>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
  props: {
    tagInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      popoverVisible: false,
      keyword: '',
      catalogList: [],
      selected: [],
      params: {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      },
      totalSize: 0,
      breadLeft: 0
    }
  },
  computed: {
    showList() {
      if (!this.selected.length) return cloneDeep(this.catalogList)
      else {
        return this.selected[this.selected.length - 1]._children
      }
    }
  },
  methods: {
    getBreadStyle() {
      // 面包屑样式
      this.$nextTick(() => {
        let totalWidth = 0
        let breadLeft = 0
        const bread = this.$refs.factoryBread
        if (bread) {
          let breadWidth = bread.$el.clientWidth
          for (let i = 0; i < bread.$children.length; i++) {
            totalWidth += bread.$children[i].$el.clientWidth
          }
          if (totalWidth > breadWidth) breadLeft = -(totalWidth - breadWidth + 20)
        }
        this.breadLeft = breadLeft
      })
    },
    openPanel() {
      if (this.catalogList.length) return
      this.$ajax({
        url: this.$ajax.setUrl('tagFactory/catalogClassList'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (data.data && data.data.length) {
            var catalogs = this.$utils.arrayToTree(data.data.slice(1), {
              id: 'catalogId',
              pid: 'parentCatalogId',
              mainSort: 'catalogLevel'
            })
            this.catalogList = catalogs
          }
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    handleClickCatalog(item) {
      if (item.tail) {
        let result = Object.assign({}, item, { _children: [] })
        this.selected.push(result)
        this.getResults(item)
      } else {
        if (!item._children || !item._children.length)
          item._children = this.findCatalog(cloneDeep(this.catalogList), item.catalogId)
        this.selected.push(item)
      }
      this.getBreadStyle()
    },
    handleCurrentChange(val) {
      this.params.currentPageNum = val
      this.getResults()
    },
    search() {
      if (!this.keyword.trim().length) {
        if (!this.selected.length || !this.selected[0].catalogId) this.selected = []
        else this.clearKeyword()
        return
      }
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.getResults()
    },
    getResults(item) {
      this.params.queryParams.listType = 1
      this.params.queryParams.assetType = 1
      this.params.queryParams.assetNm = this.keyword
      if (item && item.catalogId) this.params.queryParams.catalogId = item.catalogId
      else if (this.selected.length)
        this.params.queryParams.catalogId = this.selected[this.selected.length - 1].catalogId
      this.$emit('toggleLoading', true)
      this.$ajax({
        url: this.$ajax.setUrl('tagFactory/pageList'),
        method: 'get',
        params: this.$ajax.setParams(this.params)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (this.selected.length) this.selected[this.selected.length - 1]._children = data.data.records
          else {
            this.selected.push({ _children: data.data.records })
          }
          this.totalSize = data.data.totalSize
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.$emit('toggleLoading', false)
      })
    },
    prev() {
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.totalSize = 0
      this.keyword = ''
      this.selected.splice(this.selected.length - 1, 1)
      this.getBreadStyle()
    },
    findCatalog(list, targetId) {
      var children = []
      for (let i = 0; i < list.length; i++) {
        if (list[i].catalogId === targetId) {
          children = list[i]._children || []
          break
        } else {
          if (list[i]._children) {
            children = this.findCatalog(list[i]._children, targetId)
            if (children.length) break
          }
        }
      }
      return children
    },
    clearKeyword() {
      if (this.selected[this.selected.length - 1].catalogId) {
        if (this.selected[this.selected.length - 1].tail) {
          this.getResults(this.selected[this.selected.length - 1])
        } else {
          this.selected[this.selected.length - 1]._children = this.findCatalog(
            cloneDeep(this.catalogList),
            this.selected[this.selected.length - 1].catalogId
          )
        }
      } else this.selected.splice(this.selected.length - 1, 1)
    },
    clearSearch() {
      this.keyword = ''
      this.clearKeyword()
    },
    changeTab(index) {
      if (index === this.selected.length - 1) return
      this.keyword = ''
      this.selected.splice(index + 1)
      this.getBreadStyle()
    },
    handleClick(item) {
      this.$emit('confirm', item)
      this.popoverVisible = false
    }
  }
}
</script>

<style lang="scss">
.selector-tag {
  display: inline-block;
  max-width: 105px;
  padding: 3px 15px;
  margin-top: -5px;
  border: 1px solid #eee;
  border-radius: 2px;
  color: #6a86cc;
  background-color: #e6eeff;
  cursor: pointer;
  &:hover {
    border-color: #6a86cc;
  }
}
.tag-selector {
  height: 520px;
  .search-box {
    .el-input__inner {
      border-radius: 20px;
    }
    .el-input__suffix {
      top: 6px;
      right: 25px !important;
    }
    .el-input__suffix-inner {
      font-size: 18px;
      color: #4d82e9;
    }
  }
  .tab-title {
    font-size: 15px;
    font-weight: bold;
    padding: 10px 0 10px 35px;
    color: #455fbc;
    position: relative;
    .el-breadcrumb__inner {
      font-size: 15px;
      font-weight: bold;
      color: #455fbc;
      cursor: pointer;
      &:hover {
        color: #455fbc;
      }
    }
    .el-breadcrumb__item.normal .el-breadcrumb__inner {
      font-weight: normal;
    }
    svg {
      width: 18px;
      height: 18px;
      position: absolute;
      left: 10px;
      top: 7px;
      cursor: pointer;
    }
  }
  .elli {
    width: 16px;
    height: 100%;
    content: '...';
    line-height: 10px;
    background-color: #f0f4f7;
    position: absolute;
    top: 0;
    left: 0;
  }
  .asset-name {
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .tag-item {
    padding: 0 30px 0 20px;
    line-height: 40px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    cursor: pointer;
    position: relative;
    &:hover {
      background-color: #c0d2f6;
      &:before {
        width: 10px;
        height: 10px;
        content: '';
        border: 2px solid rgba(#000, 0.3);
        background-color: #a8fff9;
        border-radius: 50%;
        position: absolute;
        top: 15px;
        left: 5px;
      }
    }
    .list-handler {
      position: absolute;
      top: 0;
      right: 10px;
      .plus {
        display: inline-block;
        width: 18px;
        height: 18px;
        margin-top: -5px;
        border: 1px solid #5f8eec;
        color: #5f8eec;
        line-height: 15px;
        text-align: center;
        border-radius: 50%;
        vertical-align: middle;
        i {
          font-size: 12px;
          position: static;
        }
      }
      svg {
        width: 16px;
        height: 16px;
        color: #455fbc;
        margin: -5px 5px 0 10px;
        vertical-align: middle;
      }
    }
  }
  .catalog-list {
    height: calc(100% - 40px);
    overflow-y: auto;
    li {
      padding: 0 30px 0 20px;
      line-height: 40px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      cursor: pointer;
      position: relative;
      &:hover {
        color: $theme-color;
      }
      i {
        position: absolute;
        top: 15px;
        right: 15px;
      }
    }
  }
  p {
    padding: 0 20px;
    margin: 10px 0 20px 0;
  }
  .el-pagination {
    padding: 2px 15px;
    white-space: normal;
    text-align: right;
  }
  .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: #455fbc;
  }
}
</style>
